package game;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;

public class GamePanel extends JPanel implements ActionListener {
    private final int WIDTH = 500, HEIGHT = 600;
    private final Player player;
    private final List<Meteor> meteors;
    private final Timer gameTimer;
    private long startTime;
    private boolean isRunning = true, win = false;
    private final GameFrame parent;
    private int meteorSpeed, spawnInterval;

    public GamePanel(GameFrame parent, int difficulty) {
        this.parent = parent;
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        setBackground(Color.BLACK);
        setFocusable(true);

        // 设置不同难度的陨石速度和刷新频率
        switch (difficulty) {
            case 1 -> { // 简单
                meteorSpeed = 3;
                spawnInterval = 1200;
            }
            case 2 -> { // 中等
                meteorSpeed = 5;
                spawnInterval = 800;
            }
            case 3 -> { // 困难
                meteorSpeed = 7;
                spawnInterval = 500;
            }
        }

        player = new Player(WIDTH / 2 - 25, HEIGHT - 60, 50, 50);
        meteors = new CopyOnWriteArrayList<>();

        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (!isRunning) return;
                if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                    player.move(-20, 0);
                } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                    player.move(20, 0);
                }
            }
        });

        gameTimer = new Timer(30, this);
        gameTimer.start();
        startTime = System.currentTimeMillis();

        new Thread(() -> {
            Random rand = new Random();
            while (isRunning) {
                int x = rand.nextInt(WIDTH - 40);
                meteors.add(new Meteor(x, 0, 40, 40, meteorSpeed + rand.nextInt(3)));
                try {
                    Thread.sleep(spawnInterval);
                } catch (InterruptedException ignored) {}
            }
        }).start();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (!isRunning) return;

        long elapsed = (System.currentTimeMillis() - startTime) / 1000;
        if (elapsed >= 60) {
            isRunning = false;
            win = true;
            repaint();
            gameTimer.stop();
            SwingUtilities.invokeLater(() -> parent.askRestart());
        }

        for (Meteor meteor : meteors) {
            meteor.fall();
            if (meteor.getBounds().intersects(player.getBounds())) {
                isRunning = false;
                win = false;
                repaint();
                gameTimer.stop();
                SwingUtilities.invokeLater(() -> parent.askRestart());
            }
        }

        meteors.removeIf(m -> m.getY() > HEIGHT);
        repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        player.draw(g);
        for (Meteor m : meteors) {
            m.draw(g);
        }

        g.setColor(Color.WHITE);
        g.setFont(new Font("Arial", Font.BOLD, 20));
        long seconds = (System.currentTimeMillis() - startTime) / 1000;
        g.drawString("已坚持: " + seconds + " 秒", 10, 25);

        if (!isRunning) {
            g.setFont(new Font("Arial", Font.BOLD, 32));
            g.setColor(win ? Color.GREEN : Color.RED);
            String msg = win ? "你赢了！成功闪避60秒！" : "游戏结束，被陨石击中！";
            g.drawString(msg, 50, HEIGHT / 2);
        }
    }
}
